﻿using System;
using System.Threading;
using System.Windows.Forms;
using DCS.AdministrationClient.DCS_Service;
using DCS.AdministrationClient.Properties;
using DCS.Extensions.WindowsForms;

namespace DCS.AdministrationClient.Forms
{
    public partial class ConnectionForm : Form
    {
        private readonly Action serviceConnected;

        public ConnectionForm()
        {
            InitializeComponent();
            serviceConnected = OnServiceConnected;
        }

        private void OnServiceConnected()
        {
            this.InvokeSync(() =>
                                {
                                    new GreetingsForm().Show();
                                    Hide();
                                });
        }

        private void ConnectButtonClick(object sender, EventArgs e)
        {
            new Thread(TryConnect).Start();
        }

        private void TryConnect()
        {
            try
            {
                throbber.SafeVisibleSet(true);
                connectButton.SafeDisable();

                Connect();

                throbber.SafeVisibleSet(false);
                connectButton.SafeEnable();
                Program.Context.Url = ipAddress.SafeTextGet();
                serviceConnected();
            }
            catch (Exception)
            {
                throbber.SafeVisibleSet(false);
                connectButton.SafeEnable();
                MessageBox.Show(Resources.connectionFailedMessage,
                                Resources.connectionFailedTitle,
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void Connect()
        {
            Program.Context.DcsService =
                new DcsService(string.Format("http://{0}/DcsService.asmx",
                                             ipAddress.SafeTextGet()));
            Program.Context.StartSession();
        }

        private void CancelClick(object sender, EventArgs e)
        {
            this.SafeClose();
        }

        private void ipAddress_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                new Thread(TryConnect).Start();
            }
        }
    }
}
